package com.wipz.eoa.iphone.officesupplies;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import com.toft.core2.ToftException;
import com.toft.widgets.workflow.model.CompleteTaskResult;
import com.toft.widgets.workflow.provider.ApprocalAssistance;
import com.toft.widgets.workflow.utils.ConstantUtil;
import com.toft.widgets.workflow.utils.DateConvertUtil;
import com.wipz.eoa.iphone.BaseAction;
import com.wipz.eoa.iphone.businessProcess.AgencyCoreService;
import com.wipz.eoa.iphone.businessProcess.TaskTransitionService;
import com.wipz.eoa.iphone.businessProcess.WorkFlowCoreService;
import com.wipz.eoa.iphone.util.Constants;

public class OfficeSuppliesApplyAction extends BaseAction {
	private static final long serialVersionUID = 2870989336581745718L;
	private IOfficeSuppliesApplyService service;
	private AgencyCoreService agencyCoreService;
	private TaskTransitionService taskTransitionService;
	private WorkFlowCoreService workFlowCoreService;


	public void setWorkFlowCoreService(WorkFlowCoreService workFlowCoreService) {
		this.workFlowCoreService = workFlowCoreService;
	}

	private List list;//办公用品申请列表
	private Map detail;//办公用品申请详情
	private Map bxSubmit;
	private Map insert;
	
	
	public Map getInsert() {
		return insert;
	}

	public void setInsert(Map insert) {
		this.insert = insert;
	}

	public Map getBxSubmit() {
		return bxSubmit;
	}

	public void setBxSubmit(Map bxSubmit) {
		this.bxSubmit = bxSubmit;
	}

	public void setTaskTransitionService(TaskTransitionService taskTransitionService) {
		this.taskTransitionService = taskTransitionService;
	}

	public void setAgencyCoreService(AgencyCoreService agencyCoreService) {
		this.agencyCoreService = agencyCoreService;
	}

	public IOfficeSuppliesApplyService getService() {
		return service;
	}
	public void setService(IOfficeSuppliesApplyService service) {
		this.service = service;
	}
	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}
	public Map getDetail() {
		return detail;
	}
	public void setDetail(Map detail) {
		this.detail = detail;
	}
/**
 * 办公用品申请列表
 * @return
 */
	public String list(){
		Map<String,Object> parameterMap=new HashMap<String,Object>();
		parameterMap.put("COMMITERCODE", getRequest().getParameter("COMMITERCODE"));
		parameterMap.put("BILLCODE", getRequest().getParameter("BILLCODE"));
		parameterMap.put("CATEGORYCODE",getRequest().getParameter("CATEGORYCODE"));
		parameterMap.put("PROCESS_STATUS", getRequest().getParameter("PROCESS_STATUS"));
		parameterMap.put("APPLYDATE", getRequest().getParameter("APPLYDATE"));
		parameterMap.put("order", getRequest().getParameter("order"));
		parameterMap.put("sort",getRequest().getParameter("sort"));
		list=service.queryList("officesupplies.list", parameterMap);
		return SUCCESS;
	}
	
	/**
	 * 办公用品详情
	 * @return
	 */
	public String detail(){
		String id=getRequest().getParameter("id");
		String taskId = getRequest().getParameter("taskId");
		String COMMITERCODE = this.getRequest().getParameter("COMMITERCODE");
		if(StringUtils.isNotEmpty(id)){
			Map params = new HashMap();
			params.put("id", id);
			detail=(Map)service.queryOne("officesupplies.queryone", params);
			Map newMap = (Map) service.queryOne("businessProcess.queryByCode",detail);
			String processId = newMap == null ? "":(String)newMap.get("PROCESSID") ;
			detail.put("processInstanceId", processId);
			if(null == COMMITERCODE || COMMITERCODE.isEmpty()) {
				return SUCCESS;
			}
			String userId = (String) service.queryOne("user.queryId",COMMITERCODE);
			detail = agencyCoreService.agencyList(Constants.OFFICESUPPLIESAPPLY_BUSINESS_ID, userId,detail);
			
			if(null == taskId || taskId.isEmpty()) {
				return SUCCESS;
			}
			
			detail.put("taskId", taskId);
			List list =(taskTransitionService.getTaskTransition(taskId));
			Map url = new HashMap();
			StringBuffer bf = new StringBuffer();
			bf.append("/officeSupplies/OfficeSuppliesApplyAction_bxSubmit.action?id=");
			bf.append(id);
			bf.append("&COMMITERCODE=");
			bf.append(COMMITERCODE);
			bf.append("&taskId=");
			bf.append(taskId);
			url.put("url", bf.toString());
			list.add(url);
			detail.put("button", list);
			
		}
		return SUCCESS;
	}
	
	/**
	 * 办公用品申请审批
	 * @return
	 * 2012-2-20 下午04:37:48
	 */
	 public String bxSubmit() {
		//获取ID
			String id = this.getRequest().getParameter("id");
			//用户代号
			String COMMITERCODE = this.getRequest().getParameter("COMMITERCODE");
			if(id.isEmpty() || COMMITERCODE.isEmpty()) {
				return SUCCESS;
			}
			//任务唯一标识taskId
			String taskId =  this.getRequest().getParameter("taskId");
			//处理意见
			String commentContent =  this.getRequest().getParameter("comment");
			try {
				String s = new String(commentContent.getBytes("iso-8859-1"),"utf-8");
				commentContent = java.net.URLDecoder.decode(s, "utf-8");
			} catch (UnsupportedEncodingException e) {
				return SUCCESS;
			}

			//流向
			String transition = this.getRequest().getParameter("name");
			//处理类型
			String typeaccept = this.getRequest().getParameter("pass");
			Map param = new HashMap();
			
			param.put("id", id);
			Map officesuppliesMap =(Map)service.queryOne("officesupplies.queryone", param);
			Map processidMap =(Map)service.queryOne("businessProcess.queryByCode",officesuppliesMap);
			param.put("PROCESSID", processidMap.get("PROCESSID"));
			param.put("COMMITERCODE", COMMITERCODE);
			param.put("taskId", taskId);
			param.put("comment", commentContent);
			param.put("transition", transition);
			param.put("pass",typeaccept);
			Map mapUuid = (Map)service.queryOne("user.queryAll", COMMITERCODE);
			param.put("uuitId",mapUuid.get("ORGID") );
			bxSubmit = service.bxSubmit(param);
		 return SUCCESS;
	 }
	public String delete(){
		String id=getRequest().getParameter("id");
		if(StringUtils.isNotEmpty(id)){
			service.delete("officesupplies.delete", id);
		}
		return SUCCESS;
	}
	
	
	public String addOrUpdate(){
		String id = this.getRequest().getParameter("id");
		Map<String, Object> params=new HashMap<String,Object>();
		if (null == id || "".equals(id)){
			service.insert("", params);
		}else{
			params.put("ID",id);
			service.update("", params);
		}
		return SUCCESS;
	}
	
	public String sent() {
		String commitercode = this.getRequest().getParameter("COMMITERCODE");
		String usercode = (String) this.getSession().get(Constants.USERINFO_USERCODE);
		if(null == usercode || "".equals(usercode)) {
		this.getSession().put(Constants.USERINFO_USERCODE, commitercode);
		}
		return SUCCESS;
	}
	
	public String insert() {
		String uuid = com.toft.utils.UUIDHexGenerator.getInstance().generate();
		String billCode = Constants.getBillCode("BG");
		
		String  commiter = this.getRequest().getParameter("COMMITER");
		String  COMMITERCODE = (String) this.getSession().get(Constants.USERINFO_USERCODE);
		String  department = this.getRequest().getParameter("DEPARTMENT");
		String agencyId = this.getRequest().getParameter("AGENCY");
		String supliestype = this.getRequest().getParameter("SUPLIESTYPE");
		String suppliesquantity = this.getRequest().getParameter("SUPPLIESQUANTITY");
		String describe = this.getRequest().getParameter("DESCRIBE");
		String categorycode = this.getRequest().getParameter("SUPLIESTYPE");
		
		Map params = new HashMap();
		params.put("ID", uuid);
		params.put("BILLCODE", billCode);
		params.put("COMMITER", commiter);
		params.put("COMMITERCODE", COMMITERCODE);
		params.put("DEPARTMENT", department);
		params.put("APPLYDATE", DateConvertUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss") );
		params.put("SUPLIESTYPE", supliestype);
		params.put("SUPPLIESQUANTITY", suppliesquantity);
		params.put("DESCRIBE", describe);
		params.put("CATEGORYCODE", categorycode);
		Map categorymap = (Map) service.queryOne("categoryDic.querybycode", categorycode);
		String isconsumable = (String) categorymap.get("ISCONSUMABLE");
		params.put("ISCONSUMABLE", isconsumable);
		String ownerdept = (String) service.queryOne("user.queryAgencyBycode", COMMITERCODE);
		params.put("OWNERDEPT", ownerdept);
		
		
		
		//插入
		service.insert("officesupplies_Apply.insert", params);
		
		StringBuffer remark = new StringBuffer();
		remark.append("申请办公用品: ")
			  .append(this.getRequest().getParameter("SUPLIESTYPE"))
			  .append(",数量")
		      .append(this.getRequest().getParameter("SUPPLIESQUANTITY"));
		Map putMap = new HashMap();
		putMap.put(ConstantUtil.BUSINESS_RECORE_ID, uuid);
		putMap.put(ConstantUtil.BUSINESS_SN, billCode);
		putMap.put(ConstantUtil.BUSINESS_MONEY, remark.toString());
		
		String nextApprovaler = "";
		
		Map usermap = (Map) service.queryOne("user.queryUserList", COMMITERCODE);
		String userid = (String) usermap.get("ID");
		//查询 职责ID
		
		Map mapparams = new HashMap();
		mapparams.put("USERID",userid);
		mapparams.put("AGENCYID", agencyId);
		Map r = new HashMap();									
		r = (Map) service.queryOne("agency.queryDutyIDByUserIDAgencyID", mapparams);
		String dutyId = (String) r.get("DUTYID");
		
		putMap.put("dutyId", dutyId);
		putMap.put("agencyId", agencyId);
		putMap.put("userCode", COMMITERCODE);
		//业务类型ID
		String businessid = Constants.OFFICESUPPLIESAPPLY_BUSINESS_ID;
		
		//流程编号，如果存在则为重新提交，如果为null则为新单据
		String processinstanceID = null;
		//执行任务后的结果参数
		CompleteTaskResult completeTaskResult = null;
		Map newParams = new HashMap();
		Iterator iterator = putMap.entrySet().iterator();
		while(iterator.hasNext()){
			Entry entry = (Entry)iterator.next();
			newParams.put(entry.getKey(), entry.getValue());
		}
	
		try {
			//首次提交		
				
				try {
					completeTaskResult = workFlowCoreService.submitProcess(agencyId, businessid, newParams,
							COMMITERCODE);
				} catch (ToftException e) {
					e.printStackTrace();
				}
				processinstanceID = (String)completeTaskResult.getProcessInstanceId();	 //获得工作流实例ID
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String currentDate = sdf.format(new Date());
				
				Map processMap = new HashMap();
				processMap.put("BILLID", billCode);
				processMap.put("PROCESSID", processinstanceID);
				processMap.put("BUSINESSTYPE", businessid);
				service.insert("businessProcess.insert", processMap);
			
			
			//查询下级审批人
			nextApprovaler = (String)completeTaskResult.getNextOperators();
			
		
			Map map = new HashMap();
				map.put("ID", uuid);
				map.put("PROCESS_STATUS", "1");
				map.put("NEXTAPPROVALER", nextApprovaler);
				// 更改单据状态为已提交待审批
				service.update("officesupplies_Apply.updateProcessStatus", map);
			
			//当存在下级处理人时,传入下级处理人信息,不存在时,单据审批结束
			if (!"".equals(processinstanceID)) {
				if(nextApprovaler != null && !"".equals(nextApprovaler)){
					insert = new HashMap();
					insert.put("success", true);
					insert.put("NEXTOPERATOR", nextApprovaler);
				}
			} 
		} catch (Exception je) {
			ApprocalAssistance.rollbackTransaction();
			je.printStackTrace();
		}
		return SUCCESS;
		
	}
	
	
	
}
